import pkg from './package.json';
import del from 'rollup-plugin-delete';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import commonjs from '@rollup/plugin-commonjs';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import babel from '@rollup/plugin-babel';
import postcss from 'rollup-plugin-postcss';
import postcssImport from 'postcss-preset-env';
import cssnano from 'cssnano';
import pix2rem from 'postcss-pxtorem';
import typescript from '@rollup/plugin-typescript';

const configDic = {
    cjs: {
        del: ['lib/*'],
        output: { format: 'cjs', dir: 'lib' },
        ts: {
            rootDir: 'src/',
            declaration: true,
            declarationDir: 'lib/',
        },
    },
    esm: {
        del: ['es/*'],
        output: { format: 'esm', dir: 'es' },
        ts: {
            rootDir: 'src/',
            declaration: true,
            declarationDir: 'es/',
        },
    },
};

const generateConfgig = (format) => {
    return {
        input: pkg.source,
        output: {
            ...configDic[format].output,
            preserveModules: true,
            preserveModulesRoot: 'src',
            exports: 'auto',
        },
        plugins: [
            del({ targets: configDic[format].del }),
            peerDepsExternal(),
            commonjs(),
            nodeResolve(),
            typescript(configDic[format].ts),
            babel({
                exclude: 'node_modules/**',
                // 如果是lib，推荐设置为runtime，作为peerDependency
                babelHelpers: 'bundled',
            }),
            postcss({
                plugins: [
                    postcssImport(),
                    // 如果不需要自动转rem，就把这一行注释掉
                    pix2rem({ propList: ['*'], rootValue: 100, exclude: /node_modules/i }),
                    cssnano(),
                ],
                sourceMap: false,
                // 不extract，就会每个组件中动态插入style节点到head中
                // extract，会把所有的css打包成index.css，需要在项目中手动引入
                extract: false,
            }),
        ],
        external: Object.keys(pkg.peerDependencies || {}),
    };
};

export default [
    // commonjs
    generateConfgig('cjs'),
    // esm
    generateConfgig('esm'),
];
